﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Lucene;
using Lucene.Net.Index;
using Quartz;
using log4net;
using Quartz.Impl;
using LuceneNetServices.QuzrtzNetCommon;
namespace LuceneNetServices
{
    public partial class Service1 : ServiceBase
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(Service1));
        

        public Service1()
        {
            log4net.Config.XmlConfigurator.Configure();
            InitializeComponent();
            SchedulerManager.GetSchedulerFactory().GetScheduler().ListenerManager.AddJobListener(SchedulerManager.GetJobListener());
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                JobKey jobKey = new JobKey("CreateIndex", "CreateIndexGroup");

                IJobDetail jobDetail = JobBuilder.Create().WithIdentity(jobKey).OfType(typeof(Jobs.QuzrtaNet)).Build();

                ITrigger trigger = TriggerBuilder.Create().WithCronSchedule("0 0/59 * * * ?").StartNow().Build();
                SchedulerManager.GetScheduler().ScheduleJob(jobDetail, trigger);
                logger.Info("任务 " + jobDetail.Key.Group + "已经调度陈功");
                if (SchedulerManager.GetScheduler().IsStarted == false)
                {
                    SchedulerManager.GetScheduler().Start();
                    logger.Info("服务已经成功启动");
                }
            }
            catch (Exception ex)
            {
                logger.Error("服务启动失败", ex);
                if (this.CanStop == true)
                {
                    this.Stop();
                }
            }
        }

        protected override void OnStop()
        {
            try
            {
                if (SchedulerManager.GetScheduler().IsShutdown == false)
                {
                    SchedulerManager.GetScheduler().Shutdown();
                    logger.Info("Quartz服务成功终止");
                }
            }
            catch (Exception ex)
            {
                logger.Error("服务停止失败",ex);
            }

        }
        protected override void OnPause()
        {
            
        }

        protected override void OnContinue()
        {
            
        }
    }
}
